package com.lysj.website.auth.service;

import com.lysj.website.auth.domain.Permission;
import com.lysj.website.auth.repository.PermissionRepository;
import com.lysj.website.common.constant.CommonConstant;
import com.lysj.website.common.spring.base.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * @author zk
 * @description 权限表服务层
 * @create 2018-07-25 15:32:54
 **/
@Slf4j
@Service
@Transactional
public class PermissionService implements BaseService<Permission> {

    @Resource
    private PermissionRepository permissionRepository;

    @PersistenceContext
    private EntityManager em;

    @Override
    public PermissionRepository getRepository() {
        return permissionRepository;
    }

    public List<Permission> findByUserId(String userId) {
        StringBuilder sb = new StringBuilder();
        sb.append("select distinct p from User u" +
                " ,UserRole ur ,RolePermission rp ,Permission p where u.id = ur.userId and ur.roleId = rp.roleId and p.id = rp.permissionId" +
                " and u.id = ? and p.delFlag =");
        sb.append(CommonConstant.NORMAL_FLAG);
        sb.append("  order by p.sortOrder");
        Query query = em.createQuery(sb.toString(), Permission.class).setParameter(1, userId);
        List<Permission> list = query.getResultList();
        return list;
    }

    public List<Permission> findByRoleId(String roleId){
        StringBuilder sb = new StringBuilder();
        sb.append("select p from RolePermission rp ,Permission p where p.id = rp.permissionId and rp.roleId = ? and p.delFlag =");
        sb.append(CommonConstant.NORMAL_FLAG);
        sb.append("  order by p.sortOrder");
        Query query = em.createQuery(sb.toString(), Permission.class).setParameter(1, roleId);
        List<Permission> list = query.getResultList();
        return list;
    }

    public List<Permission> findByLevelOrderBySortOrderDesc(Integer level) {
        return permissionRepository.findByLevelOrderBySortOrder(level);
    }


    public List<Permission> findByParentIdOrderBySortOrder(String parentId) {
        return permissionRepository.findByParentIdOrderBySortOrder(parentId);
    }

}